package com.dts.server.common.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName:  EncryptUtil
 * @author 范旭蛟
 * @date 2021年9月19日 下午8:56:04
 * @Description: sha-256加密
 */
public class EncryptUtil {
    
    private static Logger log = LoggerFactory.getLogger(EncryptUtil.class);    
    
    /**
     * 将密码加密
     * @param password 密码
     * @return 返回加密后字符串
     */
    public static String encode(String password){
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            byte[] array = messageDigest.digest(password.getBytes("UTF-8"));
            return toHexStr(array, false);
        } catch (NoSuchAlgorithmException e) {
            log.error("加密失败", e);
        } catch (UnsupportedEncodingException e) {
            log.error("字符串编码格式错误", e);
        }
        return null;
    }
    
    /**
     * 将字节数组转换成16进制字符串
     * @param array 字节数组
     * @param space 是否去除空格
     * @return 返回16进制字符串
     */
    public static String toHexStr(byte[] array, boolean space){
        char[] mChars = "0123456789ABCDEF".toCharArray();
        StringBuilder sb = new StringBuilder();  
        for (int n=0; n<array.length; n++){
            sb.append(mChars[(array[n] & 0xFF) >> 4]);  
            sb.append(mChars[array[n] & 0x0F]);
            if(space)sb.append(" ");
        }  
        return sb.toString().trim().toUpperCase(Locale.US);
    }

}
